package com.cpit.qualitycontrol.service.impl;

import com.cpit.platform.common.constant.SystemConstant;
import com.cpit.platform.common.entity.TableDataQueryCondition;
import com.cpit.platform.common.entity.TableJsonData;
import com.cpit.platform.common.utils.Encodes;
import com.cpit.platform.common.utils.FileUtil;
import com.cpit.platform.config.UploadPathConfig;
import com.cpit.platform.dao.OrganizationRepository;
import com.cpit.platform.dao.UserRepository;
import com.cpit.platform.dao.UserToRoleRepository;
import com.cpit.platform.dto.OperLog;
import com.cpit.platform.dto.Organization;
import com.cpit.platform.dto.User;
import com.cpit.platform.dto.UserToRole;
import com.cpit.platform.log.LogOperator;
import com.cpit.platform.security.service.UserInfo;
import com.cpit.platform.service.OperLogService;
import com.cpit.qualitycontrol.common.constant.ActivitiConstant;
import com.cpit.qualitycontrol.common.constant.RoleConstant;
import com.cpit.qualitycontrol.common.enums.*;
import com.cpit.qualitycontrol.dao.*;
import com.cpit.qualitycontrol.dao.jpqlquery.SubTaskQueryRepository;
import com.cpit.qualitycontrol.entity.*;
import com.cpit.qualitycontrol.service.*;
import com.cpit.qualitycontrol.vo.SubTaskCheckVo;
import com.cpit.qualitycontrol.vo.SubTaskImageVo;
import com.cpit.qualitycontrol.vo.SubTaskSubmitCoordinateVo;
import com.cpit.qualitycontrol.vo.SubTaskSubmitVo;
import com.github.pagehelper.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created by xxx on 2017/10/10.
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class SubTaskServiceImpl implements SubTaskService {

    private final String loggerName = this.getClass().getName();

    @Autowired
    ActivitiServiceImpl activitiService;

    @Autowired
    SubTaskQueryRepository subTaskQueryRepository;

    @Autowired
    SubTaskCrudRepository subTaskCrudRepository;

    @Autowired
    SubTaskBusinessDataCrudRepository subTaskBusinessDataCrudRepository;

    @Autowired
    SubTaskImageCrudRepository subTaskImageCrudRepository;

    @Autowired
    SubTaskProcessInfoCrudRepository subTaskProcessInfoCrudRepository;

    @Autowired
    UserRepository userRepository;

    @Autowired
    CommonService commonService;

    @Autowired
    WorkOrderCrudRepository workOrderCrudRepository;

    @Autowired
    OrganizationRepository organizationRepository;

    @Autowired
    UploadPathConfig uploadPathConfig;

    @Autowired
    ProcessRuleService processRuleService;

    @Autowired
    DeviceService deviceService;

    @Autowired
    OperLogService operLogService;

    @Autowired
    UserToRoleRepository userToRoleRepository;

    @Autowired
    private UserToProductLineService userToProductLineService;

    @Override
    public List<SubTask> queryTodoSubTaskByUserId(Integer userId, int page, int size, String order, String orderBy,
                                                  Long productLineId, String projectName, String constructionTeamName,
                                                  String deviceName, Long deviceTypeId, Long workOrderTypeId,
                                                  Integer subTaskState, Boolean isHistory, String addr) {

        User user = userRepository.findById(userId);
        List<UserToRole> userToRoleList = userToRoleRepository.findByUserId(userId);

        //判断是否是工程部人员或产品线人员
        Boolean isEnginneringDept = false;
        List<Integer> roleIdList = userToRoleList.stream().map(
                userToRole -> userToRole.getRoleId()).collect(Collectors.toList());
        if (roleIdList.contains(RoleConstant.ROLE_POTEVIO_ENGINEERING_DEPT) || roleIdList.contains(RoleConstant.ROLE_POTEVIO_PRODUCTLINE)) {
            isEnginneringDept = true;
        }
        List<String> executionIDList = null;

        if (isHistory == false) {
            executionIDList = activitiService.queryTaskExecutionIDByUserId(userId, user.getOrganizationCode(), isEnginneringDept);
        } else {
            executionIDList = activitiService.queryHistoryTaskExecutionIdsByUserId(userId, user.getOrganizationCode());
        }

        if (executionIDList == null || executionIDList.size() == 0) {
            return new ArrayList<>();
        }

        Sort.Direction der = order.equals(SystemConstant.DIRECTION_ASC) ? Sort.Direction.ASC : Sort.Direction.DESC;
        PageRequest request = new PageRequest(page - 1, size, new Sort(der, orderBy));

        List<UserToProductLine> list = userToProductLineService.findByUserId(getLoginUser().getId());
        if (list != null && list.size() > 0) {//产品线角色
            productLineId = new Long((long) list.get(0).getProductLineId());
        }

        return subTaskQueryRepository.querySubTask(productLineId,
                projectName, constructionTeamName, deviceName, deviceTypeId,
                workOrderTypeId, subTaskState, executionIDList, request, addr).getContent();
    }

    @Override
    public List<SubTask> qualifiedRate(Integer userId, int page, int size, String order, String orderBy,
                                       Long productLineId, String projectName, String constructionTeamName,
                                       String beginTime, String endTime, Integer auditCount) {

        Sort.Direction der = order.equals(SystemConstant.DIRECTION_ASC) ? Sort.Direction.ASC : Sort.Direction.DESC;
        PageRequest request = new PageRequest(page - 1, size, new Sort(der, orderBy));

//        todo 待开发
        return null;
    }

    @Override
    public SubTask querySubTaskById(Long subTaskId) {

        SubTask subTask = subTaskQueryRepository.querySubTaskById(subTaskId);

        if (subTask != null) {

            SubTaskBusinessData subTaskBusinessData = subTaskBusinessDataCrudRepository
                    .findBySubTaskId(subTaskId);
            List<SubTaskImage> subTaskImageList = subTaskImageCrudRepository
                    .findAllBySubTaskIdOrderBySubImageIdAsc(subTaskId);
            List<SubTaskProcessInfo> subTaskProcessInfoList = subTaskProcessInfoCrudRepository
                    .findAllBySubTaskIdOrderByTaskProcessInfoIdDesc(subTaskId);

            subTask.setSubTaskBusinessData(subTaskBusinessData);
            subTask.setSubTaskImageList(subTaskImageList);
            subTask.setSubTaskProcessInfoList(subTaskProcessInfoList);

            return subTask;
        } else {
            return null;
        }
    }

    @Override
    public List<SubTask> findByOrganizationTeamId(Long organizationTeamId) {
        return subTaskCrudRepository.findByOrganizationTeamId(organizationTeamId);
    }

    @Override
    public TableJsonData findByConditionJqg(Integer userId, TableDataQueryCondition cond, Boolean isHistory) {
        PageRequest request = ServiceUtils.getPageRequestByTableDataQueryCondition(cond);

        User user = userRepository.findById(userId);
        List<UserToRole> userToRoleList = userToRoleRepository.findByUserId(userId);

        //判断是否是工程部人员或产品线人员
        Boolean isEnginneringDept = false;
        List<Integer> roleIdList = userToRoleList.stream().map(
                userToRole -> userToRole.getRoleId()).collect(Collectors.toList());
        if (roleIdList.contains(RoleConstant.ROLE_POTEVIO_ENGINEERING_DEPT) || roleIdList.contains(RoleConstant.ROLE_POTEVIO_PRODUCTLINE)) {
            isEnginneringDept = true;
        }

        List<String> executionIDList = null;
        if (isHistory == false) {
            executionIDList = activitiService.queryTaskExecutionIDByUserId(userId,
                    user.getOrganizationCode(), isEnginneringDept);
        } else {
            executionIDList = activitiService.queryHistoryTaskExecutionIdsByUserId(userId, user.getOrganizationCode());
        }
//        List<String> executionIDList = activitiService.queryTaskExecutionIDByUserId(userId);
        if (executionIDList == null || executionIDList.size() == 0) {
            return new TableJsonData(cond, 0, new ArrayList<SubTask>());
        }

        Map queryCondMap = cond.getQueryCond();
        String productLineIdStr = (String) queryCondMap.get("productLineId");
        Long productLineId = null;
        if (StringUtil.isNotEmpty(productLineIdStr)) {
            productLineId = Long.valueOf(productLineIdStr);
        }
        List<UserToProductLine> list = userToProductLineService.findByUserId(getLoginUser().getId());
        if (list != null && list.size() > 0) {//产品线角色
            productLineId = new Long((long) list.get(0).getProductLineId());
        }

        String projectName = (String) queryCondMap.get("projectName");
        String constructionTeamName = (String) queryCondMap.get("constructionTeamName");
        String deviceName = (String) queryCondMap.get("deviceName");
        String deviceTypeIdStr = (String) queryCondMap.get("deviceTypeId");
        Long deviceTypeId = null;
        if (StringUtil.isNotEmpty(deviceTypeIdStr)) {
            deviceTypeId = Long.valueOf(deviceTypeIdStr);
        }
        String workOrderTypeIdStr = (String) queryCondMap.get("workOrderTypeId");
        Long workOrderTypeId = null;
        if (StringUtil.isNotEmpty(workOrderTypeIdStr)) {
            workOrderTypeId = Long.valueOf(workOrderTypeIdStr);
        }
        String subTaskStateStr = (String) queryCondMap.get("subTaskState");
        Integer subTaskState = null;
        if (StringUtil.isNotEmpty(subTaskStateStr)) {
            subTaskState = Integer.valueOf(subTaskStateStr);
        }

        Page<SubTask> subTaskPage = subTaskQueryRepository.querySubTask(productLineId,
                projectName, constructionTeamName, deviceName, deviceTypeId,
                workOrderTypeId, subTaskState, executionIDList, request, null);

        return new TableJsonData(cond, subTaskPage.getTotalElements(), subTaskPage.getContent());
    }

    private void saveSubTask(SubTask subTask, ProcessRule processRule, SubTaskSubmitVo subTaskSubmitVo) throws Exception {
        //处理图片
        List<SubTaskImageVo> imagePathList = subTaskSubmitVo.getSubTaskImageVoList();
        SubTaskImage subTaskImage;

        //生成存储目录
        String targetDir = builderSaveImageDir(subTask, processRule);

        int imagesCount = imagePathList.size();
        for (int i = 0; i < imagesCount; i++) {
            SubTaskImageVo subTaskImageVo = imagePathList.get(i);
            if (subTaskImageVo.getSubImageId() == null) {//新上载图片
                subTaskImage = new SubTaskImage();
                subTaskImage.setDeviceId(subTask.getDeviceId());
                subTaskImage.setSubTaskId(subTask.getSubTaskId());
                subTaskImage.setWorkOrderId(subTask.getWorkOrderId());
                String sourceFileName = subTaskImageVo.getImagePath();
                sourceFileName = sourceFileName.substring(sourceFileName.lastIndexOf("/") + 1);
                //图片移动，base64 路径处理
                String postfix = sourceFileName.substring(sourceFileName.lastIndexOf(".") + 1);
                String targetFileName = builderSaveImageName(subTask, processRule, i, postfix);
                FileUtil.moveFile(uploadPathConfig.getTemp(), sourceFileName, targetDir, targetFileName);
                String downBase64Str = uploadPathConfig.getWebDownloadBase64Path(targetDir + targetFileName);
                subTaskImage.setImagePath(downBase64Str);
                if (subTaskSubmitVo.isSubmit()) {//提交
                    subTaskImage.setQualified(SubTaskImageEnum.UNCHECK.getCode());
                }
                subTaskImageCrudRepository.save(subTaskImage);//
            } else {
                //取得图片数据库中的名称

                SubTaskImage subTaskImageTmp = subTaskImageCrudRepository.getOne(subTaskImageVo.getSubImageId());

                LogOperator.err(loggerName, "imageName:" + subTaskImageVo.getImagePath());

                if (subTaskImageVo.getImagePath().indexOf("download64/") == -1) {//替换
                    String imageBase64Path = subTaskImageTmp.getImagePath();
                    String targetImageName = Encodes.decodeBase64String(imageBase64Path
                            .substring(imageBase64Path.lastIndexOf("download64/") + 11));
                    LogOperator.debug(loggerName, "targetImageName path:" + targetImageName);
                    targetImageName = targetImageName.substring(targetImageName.lastIndexOf("/") + 1);
                    LogOperator.debug(loggerName, "targetImageName:" + targetImageName);

                    //图片移动，base64 路径处理
                    String sourceFileName = subTaskImageVo.getImagePath().substring(
                            subTaskImageVo.getImagePath().lastIndexOf("/") + 1);
                    FileUtil.moveFileReplace(uploadPathConfig.getTemp(), sourceFileName, targetDir, targetImageName);
                    String downBase64Str = uploadPathConfig.getWebDownloadBase64Path(targetDir + targetImageName);
                    subTaskImageTmp.setImagePath(downBase64Str);

                    if (subTaskSubmitVo.isSubmit()) {//提交
                        subTaskImageTmp.setQualified(SubTaskImageEnum.UNCHECK.getCode());
                    } else {
                        subTaskImageTmp.setQualified(SubTaskImageEnum.UNSUBMIT.getCode());
                    }
                    subTaskImageCrudRepository.save(subTaskImageTmp);
                }
            }
        }

        //处理业务数据
        SubTaskBusinessData subTaskBusinessData = subTaskBusinessDataCrudRepository
                .findBySubTaskId(subTask.getSubTaskId());
        BeanUtils.copyProperties(subTaskSubmitVo.getSubTaskBusinessDataVo(), subTaskBusinessData);
        subTaskBusinessDataCrudRepository.save(subTaskBusinessData);

    }

    @Override
    public void subTaskSubmit(Integer userId, SubTaskSubmitVo subTaskSubmitVo, OperLog operLog) throws Exception {
        //查询子系统
        SubTask subTask = subTaskQueryRepository.querySubTaskById(subTaskSubmitVo.getSubTaskId());
        //查询规则
        ProcessRule processRule = processRuleService.findByProcessRuleByDeviceTypeOrderTypeProject(
                subTask.getDeviceTypeId(), subTask.getWorkOrderTypeId(), subTask.getProjectId());

        if (subTask == null) {
            LogOperator.debug(loggerName, "任务不存在！任务ID:" + subTaskSubmitVo.getSubTaskId());
            throw new Exception("任务不存在！");
        }

        if (!subTaskSubmitVo.isSubmit()) {//只保存不提交
            operLog.setDetail("保存施工任务图片，工单名称：" + subTask.getSubTaskName());
            saveSubTask(subTask, processRule, subTaskSubmitVo);//处理图片和业务数据
            return;
        }

        operLog.setDetail("提交施工任务，工单名称：" + subTask.getSubTaskName());

        //以下为提交的处理
        String actTaskId = activitiService.queryTaskId(subTask.getActProcInstId(), subTask.getActExecutionId(),
                userId, ActivitiConstant.CONSTRUCT_TASK_DEFINITIONKEY);

        if (StringUtil.isEmpty(actTaskId)) {
            LogOperator.debug(loggerName, "任务不存在！任务ID:" + subTaskSubmitVo.getSubTaskId());
            throw new Exception("任务不存在！");
        }

        //接受任务
        activitiService.claimTask(userId, actTaskId);

        SubTaskProcessInfo currentSubTaskProcessInfo = subTaskProcessInfoCrudRepository
                .findByWorkOrderIdAndSubTaskIdAndActTaskId(subTask.getWorkOrderId(),
                        subTask.getSubTaskId(), actTaskId);

        if (currentSubTaskProcessInfo == null) {
            LogOperator.debug(loggerName, "查询不到任务对应的流程信息！任务ID:" + subTaskSubmitVo.getSubTaskId());
            throw new Exception("查询不到任务对应的流程信息！");
        }

        //处理现有流程
        currentSubTaskProcessInfo.setDescription(subTaskSubmitVo.getDescription());
        currentSubTaskProcessInfo.setOperatorId(userId);
        currentSubTaskProcessInfo.setOperatorName(userRepository.findById(userId).getDisplayName());
        currentSubTaskProcessInfo.setUiInputName(subTaskSubmitVo.getUiInputName());
        if (currentSubTaskProcessInfo.getProcessState().equals(SubTaskProcessStatusEnum.UNTREATED.getCode()))
            currentSubTaskProcessInfo.setProcessState(SubTaskProcessStatusEnum.CONSTRUCTEND.getCode());
        else if (currentSubTaskProcessInfo.getProcessState().equals(SubTaskProcessStatusEnum.UNDERCORRECT.getCode()))
            currentSubTaskProcessInfo.setProcessState(SubTaskProcessStatusEnum.CORRECTEND.getCode());

        Date currentDate = new Date();
        currentSubTaskProcessInfo.setEndTime(currentDate);
        currentSubTaskProcessInfo.setDuration(currentDate.getTime()
                - currentSubTaskProcessInfo.getAssignTime().getTime());
        subTaskProcessInfoCrudRepository.save(currentSubTaskProcessInfo);

        //处理图片和业务数据
        saveSubTask(subTask, processRule, subTaskSubmitVo);

        //开启新流程
        //1.activiti
        activitiService.completeConstructTask(currentSubTaskProcessInfo.getActTaskId(), subTask.getCheckTask().equals("是"));

        //不审核 & 审核处理
        if (!subTask.getCheckTask().equals("是")) { // 不审核

            //更新subtask 数据
            subTask.setCurrentOrganizationTeamId(null);
            subTask.setSubTaskState(SubTaskStatusEnum.END.getCode());
            subTask.setEndTaskTime(currentDate);
            subTask.setTaskDuration(currentDate.getTime() - subTask.getAssignTaskTime().getTime());
            subTaskCrudRepository.save(subTask);

            WorkOrder workOrder = workOrderCrudRepository.findOne(subTask.getWorkOrderId());
            workOrder.setProgress(getProgressByWorkOrderId(subTask.getWorkOrderId()));
            //判断整个工单是否都已结束
            if (activitiService.isProcessInstanceEndById(subTask.getActProcInstId())) {
                workOrder.setEndTime(currentDate);
                workOrder.setDuration(currentDate.getTime() - workOrder.getAssignTime().getTime());
                workOrder.setState(WorkOrderStatusEnum.END.getCode());
            }
            workOrderCrudRepository.save(workOrder);

        } else {

            //查询checkTaskId
            String actCheckTaskId = activitiService.queryTaskId(subTask.getActProcInstId(),
                    subTask.getActExecutionId(), null,
                    ActivitiConstant.CHECK_TASK_DEFINITIONKEY);

            if (StringUtil.isEmpty(actCheckTaskId)) {
                LogOperator.debug(loggerName, "任务不存在！任务ID:" + subTaskSubmitVo.getSubTaskId());
                throw new Exception("任务不存在！");
            }

            //2.currentSubTaskProcessInfo
            SubTaskProcessInfo newSubTaskProcessInfo = new SubTaskProcessInfo();
            newSubTaskProcessInfo.setProcessState(SubTaskProcessStatusEnum.UNCHECK.getCode());
            newSubTaskProcessInfo.setProcessName(TaskProcessNameEnum.CHECK.getMessage());
            newSubTaskProcessInfo.setActTaskId(actCheckTaskId);
            newSubTaskProcessInfo.setWorkOrderId(subTask.getWorkOrderId());
            newSubTaskProcessInfo.setSubTaskId(subTask.getSubTaskId());
            newSubTaskProcessInfo.setDeviceId(subTask.getDeviceId());

            subTaskProcessInfoCrudRepository.save(newSubTaskProcessInfo);

            //更新subtask 数据
            subTask.setCurrentOrganizationTeamId(2L); //todo 这块要写死普天工程部组织机构ID
            subTask.setSubTaskState(SubTaskStatusEnum.UNCHECK.getCode());
            subTaskCrudRepository.save(subTask);

            //更新workorder 数据
            WorkOrder workOrder = workOrderCrudRepository.findOne(subTask.getWorkOrderId());
            workOrder.setProgress(getProgressByWorkOrderId(subTask.getWorkOrderId()));
            workOrderCrudRepository.save(workOrder);
        }
    }

    @Override
    public void subTaskCheck(Integer userId, SubTaskCheckVo subTaskCheckVo, OperLog operLog) throws Exception {

        Date currentDate = new Date();

        SubTask subTask = subTaskQueryRepository.querySubTaskById(subTaskCheckVo.getSubTaskId());
        WorkOrder workOrder = workOrderCrudRepository.findOne(subTask.getWorkOrderId());

        if (subTaskCheckVo.getAccred()) {
            operLog.setDetail("审核通过施工任务，工单名称：" + subTask.getSubTaskName());
        } else {
            operLog.setDetail("驳回施工任务，工单名称：" + subTask.getSubTaskName());
        }

        String actTaskId = activitiService.queryTaskId(subTask.getActProcInstId(), subTask.getActExecutionId(),
                userId, ActivitiConstant.CHECK_TASK_DEFINITIONKEY);

        if (StringUtil.isEmpty(actTaskId)) {
            LogOperator.debug(loggerName, "任务不存在！任务ID:" + subTaskCheckVo.getSubTaskId());
            throw new Exception("任务不存在！");
        }

        //接受任务
        activitiService.claimTask(userId, actTaskId);

        SubTaskProcessInfo currentSubTaskProcessInfo = subTaskProcessInfoCrudRepository
                .findByWorkOrderIdAndSubTaskIdAndActTaskId(subTask.getWorkOrderId(), subTask.getSubTaskId(), actTaskId);

        if (currentSubTaskProcessInfo == null) {
            LogOperator.debug(loggerName, "查询不到任务对应的流程信息！任务ID:" + subTaskCheckVo.getSubTaskId());
            throw new Exception("查询不到任务对应的流程信息！");
        }

        //处理现有流程
        currentSubTaskProcessInfo.setDescription(subTaskCheckVo.getDescription());
        currentSubTaskProcessInfo.setOperatorId(userId);
        currentSubTaskProcessInfo.setOperatorName(userRepository.findById(userId).getDisplayName());
        currentSubTaskProcessInfo.setUiInputName("");
        if (subTaskCheckVo.getAccred()) {
            currentSubTaskProcessInfo.setProcessState(SubTaskProcessStatusEnum.CHECKADOPT.getCode());
        } else {
            currentSubTaskProcessInfo.setProcessState(SubTaskProcessStatusEnum.CHECKREJECT.getCode());
        }

        currentSubTaskProcessInfo.setEndTime(currentDate);
        currentSubTaskProcessInfo.setDuration(currentDate.getTime()
                - currentSubTaskProcessInfo.getAssignTime().getTime());
        subTaskProcessInfoCrudRepository.save(currentSubTaskProcessInfo);

        //设置审核次数
        subTask.setAuditCount(subTask.getAuditCount() + 1);

        List<SubTaskImage> subTaskImageList = subTaskImageCrudRepository
                .findAllBySubTaskIdOrderBySubImageIdAsc(subTask.getSubTaskId());
        for (SubTaskImage image : subTaskImageList) {
            image.setQualified(SubTaskImageEnum.QUALIFIED.getCode());
            subTaskImageCrudRepository.save(image);
        }

        //处理流程，结束任务，或驳回重做
        if (subTaskCheckVo.getAccred()) { //通过

            //完成审核任务 activiti
            activitiService.completeCheckTask(actTaskId, subTaskCheckVo.getAccred(), null);

            //更新subtask 数据
            subTask.setCurrentOrganizationTeamId(null);
            subTask.setSubTaskState(SubTaskStatusEnum.END.getCode());
            subTask.setEndTaskTime(currentDate);
            subTask.setTaskDuration(currentDate.getTime() - subTask.getAssignTaskTime().getTime());
            subTaskCrudRepository.save(subTask);

            //判断整个工单是否都已结束
            if (activitiService.isProcessInstanceEndById(subTask.getActProcInstId())) {
                workOrder.setEndTime(currentDate);
                workOrder.setDuration(currentDate.getTime() - workOrder.getAssignTime().getTime());
                workOrder.setState(WorkOrderStatusEnum.END.getCode());
            }

        } else { //不通过

            //处理图片
            List<Long> imageIdList = subTaskCheckVo.getRejectImageIdList();
            for (Long imageId : imageIdList) {

                //图片处理
                SubTaskImage subTaskImage = subTaskImageCrudRepository.findOne(imageId);

                subTaskImage.setQualified(SubTaskImageEnum.UNQUALIFIED.getCode());

                String imageBase64Path = subTaskImage.getImagePath();
                String imagePath = Encodes.decodeBase64String(imageBase64Path
                        .substring(imageBase64Path.lastIndexOf("download64/") + 11));
                String imageName = imagePath.substring(imagePath.lastIndexOf("/") + 1);

                try {
//                    FileUtil.deleteFileByFilePath(imagePath);
                    FileUtil.moveFileReplace(imagePath, "", uploadPathConfig.getUnqualified(), imageName);
                } catch (Exception e) {
                    LogOperator.err(loggerName,
                            "FileUtil.moveFile(imagePath) = [" + imagePath + "]", e);
                }

                //记录处理
                String downBase64Str = uploadPathConfig.getWebDownloadBase64Path(uploadPathConfig.getUnqualified()
                        + "/" + imageName);
                subTaskImage.setImagePath(downBase64Str);
                subTaskImageCrudRepository.save(subTaskImage);
            }

            //查询施工组织机构，查询组织下所有人
            Organization organization = organizationRepository.findById(subTask.getOrganizationTeamId().intValue());
            //查询组织机构下的所有用户
//            List<User> userList = userRepository.findByOrganizationCodeStartingWith(organization.getCode());
//            //转换
//            List<Integer> constructUserList = userList.stream().map(user -> user.getId()).collect(Collectors.toList());

            //完成审核任务 activiti
            activitiService.completeCheckTask(actTaskId, subTaskCheckVo.getAccred(), organization.getCode());

            //查询 ACT constructTaskId
            String actConstructTaskId = activitiService.queryTaskId(subTask.getActProcInstId(),
                    subTask.getActExecutionId(),
                    null, ActivitiConstant.CONSTRUCT_TASK_DEFINITIONKEY);

            if (StringUtil.isEmpty(actConstructTaskId)) {
                LogOperator.debug(loggerName, "任务不存在！任务ID:" + subTaskCheckVo.getSubTaskId());
                throw new Exception("任务不存在！");
            }

            //newSubTaskProcessInfo
            SubTaskProcessInfo newSubTaskProcessInfo = new SubTaskProcessInfo();
            newSubTaskProcessInfo.setProcessState(SubTaskProcessStatusEnum.UNDERCORRECT.getCode());
            newSubTaskProcessInfo.setProcessName(TaskProcessNameEnum.CONSTRUCTION.getMessage());
            newSubTaskProcessInfo.setActTaskId(actConstructTaskId);
            newSubTaskProcessInfo.setWorkOrderId(subTask.getWorkOrderId());
            newSubTaskProcessInfo.setSubTaskId(subTask.getSubTaskId());
            newSubTaskProcessInfo.setDeviceId(subTask.getDeviceId());

            subTaskProcessInfoCrudRepository.save(newSubTaskProcessInfo);

            //更新subtask 数据
            subTask.setCurrentOrganizationTeamId(subTask.getOrganizationTeamId());
            subTask.setAuditCount(subTask.getAuditCount() + 1);
            subTask.setSubTaskState(SubTaskStatusEnum.UNDERCORRECT.getCode());
            subTaskCrudRepository.save(subTask);
        }

        //更新workorder 数据
        workOrder.setProgress(getProgressByWorkOrderId(subTask.getWorkOrderId()));
        workOrderCrudRepository.save(workOrder);
    }

    /**
     * 构建图片存储目录 -- 图片存储路径  /产品线／项目名称／设备类型／工单类型／设备编号／
     *
     * @param subTask
     * @param processRule
     * @return
     */
    private String builderSaveImageDir(SubTask subTask, ProcessRule processRule) {
        StringBuilder sb = new StringBuilder();
        sb.append(uploadPathConfig.getPath()).append("/")
                .append(subTask.getProductLineName()).append("/")
                .append(subTask.getProjectName()).append("/")
                .append(subTask.getDeviceTypeName()).append("/")
                .append(subTask.getWorkOrderTypeName()).append("/")
                .append(subTask.getDeviceId()).append("/");

        return sb.toString();
    }

    /**
     * 构建图片文件名称 -- 设备编号_流程规则名称_示例照片名称.jpg
     *
     * @param subTask
     * @param processRule
     * @return
     */
    private String builderSaveImageName(SubTask subTask, ProcessRule processRule, int ruleImageIndex, String postfix) {
        StringBuilder sb = new StringBuilder();
        sb.append(subTask.getDeviceId()).append("_")
                .append(processRule.getName()).append("_");
        if (ruleImageIndex < processRule.getProcessRuleToImageFileList().size()) {
            sb.append(processRule.getProcessRuleToImageFileList().get(ruleImageIndex).getDescription());
        } else {
            sb.append(ruleImageIndex - processRule.getProcessRuleToImageFileList().size() + 1);
        }

        return sb.append(".").append(postfix).toString();
    }

    private String getProgressByWorkOrderId(Long workOrderId) {
        List<SubTask> subTaskList = subTaskCrudRepository.findByWorkOrderId(workOrderId);
        StringBuilder sb = new StringBuilder();
        for (SubTask subTaskTmp : subTaskList) {
            sb.append(subTaskTmp.getSubTaskName());
            if (subTaskTmp.getSubTaskState().equals(SubTaskStatusEnum.UNCHECK.getCode())) {
                sb.append("(").append(SubTaskStatusEnum.UNCHECK.getMessage()).append("),");
            } else if (subTaskTmp.getSubTaskState().equals(SubTaskStatusEnum.UNTREATED.getCode())) {
                sb.append("(").append(SubTaskStatusEnum.UNTREATED.getMessage()).append("),");
            } else if (subTaskTmp.getSubTaskState().equals(SubTaskStatusEnum.UNDERCORRECT.getCode())) {
                sb.append("(").append(SubTaskStatusEnum.UNDERCORRECT.getMessage()).append("),");
            } else {
                sb.append("(").append(SubTaskStatusEnum.END.getMessage()).append("),");
            }
        }
        return sb.substring(0, sb.length() - 1).toString();
    }


    @Override
    public void subTaskSubmitCoordinate(SubTaskSubmitCoordinateVo subTaskSubmitCoordinateVo) throws Exception {
        SubTaskBusinessData subTaskBusinessData = subTaskBusinessDataCrudRepository
                .findOne(subTaskSubmitCoordinateVo.getSubTaskBusinessDataId());

        subTaskBusinessData.setLatitude(subTaskSubmitCoordinateVo.getLatitude());
        subTaskBusinessData.setLongitude(subTaskSubmitCoordinateVo.getLongitude());

        subTaskBusinessDataCrudRepository.save(subTaskBusinessData);

        //将经纬度信息更新到设备表中
        String deviceId = subTaskCrudRepository
                .getOne(subTaskSubmitCoordinateVo.getSubTaskId()).getDeviceId();
        deviceService.updateCoordinate(deviceId,
                subTaskSubmitCoordinateVo.getLongitude(), subTaskSubmitCoordinateVo.getLatitude());
    }


    /**
     * 获取登录用户信息
     *
     * @return
     */
    private User getLoginUser() {
        return ((UserInfo) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal()).getUser();
    }

//    public static void main(String[] args) {
//        String aa = "aaaa/bbb/ccc/ddd".substring("aaaa/bbb/ccc/ddd".lastIndexOf("/")+1);
//        System.out.println(aa);
//    }
}
